package main

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"strings"
)
/*
限制只能127.0.0.1登录
*/
func checkLocalhost(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ip, _, err := net.SplitHostPort(r.RemoteAddr)
		if err != nil {
			http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			return
		}
		if ip != "127.0.0.1" {
			http.Error(w, "Forbidden", http.StatusForbidden)
			return
		}
		next.ServeHTTP(w, r)
	})
}
/*
程序入口
*/
func main() {

	mux := http.NewServeMux()
    mux.HandleFunc("/excel", exportExcel)

	args := os.Args[1:]
	var port string
	for i, arg := range args {
		if arg == "port" {
			port = args[i+1]
			break
		}
	}

	if port == "" || len(port) == 0 {
		server := &http.Server{
			Addr:    "127.0.0.1:"+ port, // 监听地址为本地
			Handler: checkLocalhost(mux), // 应用自定义中间件
		}
	} else {
		server := &http.Server{
			Addr:    "127.0.0.1:9995", // 监听地址为本地
			Handler: checkLocalhost(mux), // 应用自定义中间件
		}
	}
}
/*
导出数据函数
*/
func exportExcel(w http.ResponseWriter, r *http.Request) {

	//接收HTTP请求并将数据转换为[]map
	if r.Method != http.MethodPost {
		w.WriteHeader(http.StatusMethodNotAllowed)
		return
	}

	body, err := io.ReadAll(r.Body)

	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	//map[sheet名称][每一个sheet数据][模板中的字符key]cell中要填充的值
	var excelRequest ExcelRequest
	err = json.Unmarshal(body, &excelRequest)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	f, err := Export(&excelRequest)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte(err.Error()))
		return
	}
	// 设置Content-Type为application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
	w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")

	// 添加Content-Disposition头部以指定文件名
	w.Header().Set("Content-Disposition", `attachment; filename="example.xlsx"`)

	if err := f.Write(w); err != nil {
		http.Error(w, "返回文件发生错误", http.StatusInternalServerError)
	}
	localFilePath := strings.TrimSpace(excelRequest.SaveLocalPath)
	fmt.Println(localFilePath)
	if len(localFilePath) != 0 {
		fmt.Println("保存文件" + localFilePath)
		err := f.SaveAs(localFilePath)
		if err != nil {
			print(err.Error())
		}
	}

}
